package com.zzn.bookManage.controller;

import com.zzn.bookManage.pojo.Book;
import com.zzn.bookManage.pojo.ResultEntity;
import com.zzn.bookManage.pojo.User;
import com.zzn.bookManage.service.BookService;
import com.zzn.bookManage.util.ObjectHolder;
import com.zzn.bookManage.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 跳转修改图书信息
 */

@WebServlet("/gotoEditBook")
public class GotoEditBook extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession(true); // 必定获得一个session

        User loginUser = (User) session.getAttribute("loginUser");
        boolean isAdmin = "admin".equals(loginUser.getUsername());

        int bid = 0;
        int page = 1;
        int row  = 10;

        if (StringUtil.notBlank(req.getParameter("bid"))){
            bid = Integer.parseInt(req.getParameter("bid"));
        }

        BookService bookService = ObjectHolder.getInstance().getBookService();

        ResultEntity<Book> resultEntity ;
        resultEntity = bookService.listBookById(bid,page,row);
        if (resultEntity.hasData()){
            // 查询成功
            req.setAttribute("msg",null);
            req.setAttribute("result",resultEntity);
            if (isAdmin){
                req.getRequestDispatcher("/editBook.jsp").forward(req, resp);
            }else{
                req.setAttribute("msg","没有权限");
                req.getRequestDispatcher("/userMain.jsp").forward(req, resp);
            }
        }else{
            // 查询失败
            req.setAttribute("result",resultEntity);
            req.setAttribute("msg","没有记录");
            if (isAdmin){
                req.getRequestDispatcher("/editBook.jsp").forward(req, resp);
            }else{
                req.setAttribute("msg","没有权限");
                req.getRequestDispatcher("/userMain.jsp").forward(req, resp);
            }
        }
    }
}
